package vn.com.vhc.babyui;

import vn.com.vhc.library.Uptimer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SleepActivity extends Activity {
	private Handler mHandler = new Handler();
	String times, strSleep;
	private long startTime;
	private long elapsedTime;
	private final int REFRESH_RATE = 10;
	private boolean stopped = true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addsleep);
	}
	@Override
	protected void onStart() {
		super.onStart();
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null)
		{
			strSleep = bundle.getString("TIME_SLEEP");
			String[] str = strSleep.split(":");
			startTime =System.currentTimeMillis()- (Long.parseLong(str[0])*60*60*1000 + Long.parseLong(str[1])*1000*60 +  Long.parseLong(str[2])*1000);
			showStopButton();
			mHandler.removeCallbacks(startTimer);
	        mHandler.postDelayed(startTimer, 0);
			stopped = false;
		}
	}
	public void startClick(View view) {
		showStopButton();
		stopped = false;
    	if(stopped){
    		startTime = System.currentTimeMillis() - elapsedTime;
    	}
    	else{
    		startTime = System.currentTimeMillis();
    	}
    	mHandler.removeCallbacks(startTimer);
        mHandler.postDelayed(startTimer, 0);
	}

	public void stopClick(View view) {
		hideStopButton();
		mHandler.removeCallbacks(startTimer);
    	stopped = true;
	}

	public void resetClick(View view) {
		stopped = true;
    	((TextView)findViewById(R.id.timer)).setText("00:00:00");
	}
	
	private void showStopButton(){
	    ((Button)findViewById(R.id.startButton)).setVisibility(View.GONE);
	    ((Button)findViewById(R.id.resetButton)).setVisibility(View.GONE);
	    ((Button)findViewById(R.id.stopButton)).setVisibility(View.VISIBLE);
	}

	private void hideStopButton(){
	    ((Button)findViewById(R.id.startButton)).setVisibility(View.VISIBLE);
	    ((Button)findViewById(R.id.resetButton)).setVisibility(View.VISIBLE);
	    ((Button)findViewById(R.id.stopButton)).setVisibility(View.GONE);
	}
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		Intent i = new Intent(getApplicationContext(),MainActivity.class);
		if(stopped==false)
			i.putExtra("TIME_SLEEP", times);
		startActivity(i);
	}
	private Runnable startTimer = new Runnable() {
		   public void run() {
			   elapsedTime = System.currentTimeMillis() - startTime;
			   times = new Uptimer().updateTimer(elapsedTime);
			   ((TextView)findViewById(R.id.timer)).setText(times);
			   mHandler.postDelayed(this,REFRESH_RATE);
			}
		};
		
		
}
